package city.spring.modules.medicine.controller;

import city.spring.modules.material.service.ShelflevelService;
import city.spring.modules.medicine.entity.MedicineinventoryMedicineExtEntity;
import city.spring.modules.medicine.repository.MedicineinventoryMedicineExtRepository;
import city.spring.modules.medicine.service.MedicineInventoryService;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.service.MedicineinventoryMedicineExtService;
import city.spring.modules.medicine.service.MedicinestorehouseService;
import city.spring.modules.medicine.vo.MedicineinventoryMedicineVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：药品盘点计划与药品关系表
 *
 * @author 谢金婷
 * @date 2020-07-27 09:44:32
 */
@RestController
@RequestMapping("/medicineinventory_medicine_ext")
public class MedicineInventoryMedicineController extends ApiController {
    private final MedicineinventoryMedicineExtService medicineinventoryMedicineExtService;
    private final MedicineinventoryMedicineExtRepository medicineinventoryMedicineExtRepository;
    private final MedicineInventoryService medicineInventoryService;
    private final MedicinestorehouseService storehouseService;
    private final ShelflevelService shelflevelService;
    private final MedicineService medicineService;

    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicineinventoryMedicineExtEntity, ?>> entityOrderFields;

    public MedicineInventoryMedicineController(MedicineinventoryMedicineExtService medicineinventoryMedicineExtService, MedicineinventoryMedicineExtRepository medicineinventoryMedicineExtRepository, MedicineInventoryService medicineInventoryService, MedicinestorehouseService storehouseService, ShelflevelService shelflevelService, MedicineService medicineService) {
        this.medicineinventoryMedicineExtService = medicineinventoryMedicineExtService;
        this.medicineinventoryMedicineExtRepository = medicineinventoryMedicineExtRepository;
        this.medicineInventoryService = medicineInventoryService;
        this.storehouseService = storehouseService;
        this.shelflevelService = shelflevelService;
        this.medicineService = medicineService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getMedicineinventoryId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getStorehouseId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getShelfId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getMedicineId);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getQuantity);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getInventoryquantity);
        entityOrderFields.add(MedicineinventoryMedicineExtEntity::getProfitAndLoss);
    }

    /**
     * 获取全部的 <strong>药品盘点计划与药品关系表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicineinventoryMedicineExtEntity entity) {
        LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>药品盘点计划与药品关系表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "medicineinventoryId", direction = Sort.Direction.DESC)}) Pageable pageable, MedicineinventoryMedicineVO entity) {

        QueryWrapper<? extends MedicineinventoryMedicineExtEntity> queryWrapper = buildQuery(entity);
        return success(medicineinventoryMedicineExtService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicineinventoryMedicineExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MedicineinventoryMedicineExtEntity record : page.getRecords()) {
//            try {
//                MedicinestorehouseEntity storehouseEntity = storehouseService.getById(record.getStorehouseId());
//                record.setStorehousename(storehouseEntity.getSname());
//            } catch (Exception ignore) {
//                record.setStorehouseId(null);
//                record.setStorehousename("< 找不到仓库 >");
//            }
//            try {
//                ShelflevelEntity shelflevelEntity = shelflevelService.getById(record.getShelfId());
//                record.setShelflevelname(shelflevelEntity.getSname());
//            } catch (Exception ignore) {
//                record.setShelfId(null);
//                record.setShelflevelname("< 找不到货架 >");
//            }
//            try {
//                MedicineEntity medicineEntity = medicineService.getById(record.getMedicineId());
//                record.setName(medicineEntity.getName());
//            } catch (Exception ignore) {
//                record.setMedicineId(null);
//                record.setName("< 找不到物资 >");
//            }
//        }
//        return success(page);
    }


    /**
     * Medicine
     * 获取一个 <strong>药品盘点计划与药品关系表</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

        QueryWrapper<MedicineinventoryMedicineVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicineinventoryMedicineVO> records = medicineinventoryMedicineExtService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(medicineinventoryMedicineExtService.getById(id));
    }


    /**
     * 添加一个 <strong>药品盘点计划与药品关系表</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicineinventoryMedicineExtEntity entity) {
        medicineinventoryMedicineExtService.saveMedicineinventoryMedicineExt(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>药品盘点计划与药品关系表</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicineinventoryMedicineExtEntity entity) {
        entity.setId(id);
        medicineinventoryMedicineExtService.updateMedicineinventoryMedicineExt(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>药品盘点计划与药品关系表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicineinventoryMedicineExtService.deleteMedicineinventoryMedicineExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品盘点计划与药品关系表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicineinventoryMedicineExtService.deleteMedicineinventoryMedicineExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> buildLambdaQuery(MedicineinventoryMedicineExtEntity entity) {
        LambdaQueryChainWrapper<MedicineinventoryMedicineExtEntity> lambdaQuery = medicineinventoryMedicineExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MedicineinventoryMedicineExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMedicineinventoryId()), MedicineinventoryMedicineExtEntity::getMedicineinventoryId, entity.getMedicineinventoryId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getStorehouseId()), MedicineinventoryMedicineExtEntity::getStorehouseId, entity.getStorehouseId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getShelfId()), MedicineinventoryMedicineExtEntity::getShelfId, entity.getShelfId());
        lambdaQuery.eq(entity.getMedicineId() != null, MedicineinventoryMedicineExtEntity::getMedicineId, entity.getMedicineId());
        lambdaQuery.eq(entity.getQuantity() != null, MedicineinventoryMedicineExtEntity::getQuantity, entity.getQuantity());
        lambdaQuery.eq(entity.getInventoryquantity() != null, MedicineinventoryMedicineExtEntity::getInventoryquantity, entity.getInventoryquantity());
        lambdaQuery.eq(entity.getProfitAndLoss() != null, MedicineinventoryMedicineExtEntity::getProfitAndLoss, entity.getProfitAndLoss());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicineinventoryMedicineExtEntity> buildQuery(MedicineinventoryMedicineVO entity) {
        QueryWrapper<MedicineinventoryMedicineExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicineinventoryId()), "t1.medicineinventory_id", entity.getMedicineinventoryId());
        wrapper.like(StringUtils.isNotBlank(entity.getStorehouseId()), "t1.storehouse_id", entity.getStorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t2.sname", entity.getSname());
        wrapper.like(StringUtils.isNotBlank(entity.getShelfId()), "t1.shelf_id", entity.getShelfId());
        wrapper.like(StringUtils.isNotBlank(entity.getShelflevelname()), "t3.sname", entity.getShelflevelname());
        wrapper.eq(entity.getMedicineId() != null, "t1.medicine_id", entity.getMedicineId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t4.name", entity.getName());
        return wrapper;
    }

    /**
     * 获取损益值不为空和不为0的盘点药品记录 分页展示
     *
     * @param pageable
     * @return
     */
    @GetMapping("/getInventoryWarehousingAndDelivery")
    public Object getInventoryWarehousingAndDelivery(Pageable pageable) {
        return success(medicineinventoryMedicineExtService.getInventoryWarehousingAndDelivery(pageable));
    }

}
